<template>
  <view class="popup-containerd">
    <up-navbar title="选择订单" @leftClick="handleBack" placeholder :customStyle="{ backgroundColor: '#fff', borderBottom: '1px solid #f5f5f5' }"></up-navbar>

    <view class="search-box">
      <u-input v-model="searchKeyword" placeholder="输入订单号或客户名称搜索" clearable @change="handleSearchInput"></u-input>
    </view>

    <!-- #ifdef H5 -->
    <view style="height: 20rpx"></view>
    <!-- #endif -->

    <!-- #ifdef APP-PLUS -->
    <view style="height: 20rpx"></view>
    <!-- #endif -->

    <scroll-view :style="listHeightStyle" :refresher-background="'transparent'" scroll-y class="popup-scroll" @scrolltolower="loadMoreOrders">
       <view style="padding: 0 20rpx">
         <view
             v-for="(order, index) in allGylorderNO"
             :key="order.id"
             class="order-item"
             @click="selectOrderItem(order)"
         >
           <view class="order-info">
             <text class="order-label">订单编号：</text>
             <text class="order-value">{{ order.order_sum }}</text>
           </view>
           <view class="order-arrow">
             <u-icon name="arrow-right" color="#999" size="16"></u-icon>
           </view>
         </view>
       </view>
    </scroll-view>
  </view>
</template>


<script>
import { GetgylList } from '@/apis/SupplyChain/orderAfterSales';
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';

export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 15,
      total: 0,
      allGylorderNO: [],
      isLoadingOrders: false,
      noMoreOrders: false,
      searchKeyword: '',
      SupplyChain:'',
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      appHeight: 0,
      listHeightStylePage: {},
    };
  },
  computed: {
    ...mapStores(useUserStore),
    filteredOrders() {
      if (!this.searchKeyword) return this.allGylorderNO;
      const keyword = this.searchKeyword.toLowerCase();
      return this.allGylorderNO.filter(order =>
          (order.order_sum && order.order_sum.toLowerCase().includes(keyword)) ||
          (order.customer_name && order.customer_name.toLowerCase().includes(keyword))
      );
    }
  },
  onLoad (option) {
    this.SupplyChain = option.SupplyChain
  },
  created(){
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif 

    // #ifdef APP-PLUS 
    this.listHeightStylePage = {
      height: `100vh`,
    };
    // #endif 
    let app = uni.getSystemInfoSync();
    this.appHeight = app.windowHeight;
    this.calculateListHeight();
  },
  methods: {
    calculateListHeight () {
      const windowHeight = window.innerHeight;  // 视口高度
      const navbarHeight = 52; // 导航栏高度（假设为 44px）
      const searchHeight = 51; // 搜索框高度

      // #ifdef APP-PLUS 
      this.listHeightStyle = {
        overflowY: 'hidden',
        height: `${this.appHeight - 130}px`,
      };
      // #endif 

      // #ifdef H5 
      const listHeight = windowHeight - navbarHeight - searchHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden'
      };
      // #endif
    },
    handleBack() {
      uni.navigateBack({delta: 1});
    },
    // 处理搜索输入
    handleSearchInput(value) {
      console.log('value',value);
      
      this.pageNum = 1;
      // this.noMoreOrders = false;

      // 如果有搜索关键词，使用本地过滤
      // if (!this.searchKeyword) {
      //   this.allGylorderNO = [];
        this.loadMoreOrders(value);
      // }
    },
    async loadMoreOrders(value) {
      // console.log('this.searchKeyword',this.searchKeyword);
      
      // if (this.searchKeyword || this.isLoadingOrders || this.noMoreOrders) return;

      this.isLoadingOrders = true;
      try {
        const res = await GetgylList({
          token: this.userStore.user.token,
          type: 1,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNumber: value || '',
          orderSum:value
        });

        if (res.status === 1) {
          const records = res.data?.records || [];
          this.total = res.data?.total || 0;

          if (this.pageNum === 1) {
            this.allGylorderNO = records;
          } else {
            this.allGylorderNO.push(...records);
          }

          if (records.length < this.pageSize || this.allGylorderNO.length >= this.total) {
            this.noMoreOrders = true;
          } else {
            this.pageNum += 1;
          }
        } else {
          uni.showToast({ title: res.message || '加载失败', icon: 'none' });
        }
      } catch (err) {
        console.error('加载订单失败:', err);
        uni.showToast({ title: '加载失败，请重试', icon: 'none' });
      } finally {
        this.isLoadingOrders = false;
      }
    },
    selectOrderItem(order) {
      if(this.SupplyChain == 'orderAfterSales'){
        uni.$emit('orderAfterSales', order)
      }else if(this.SupplyChain == 'orderPriceAdjustment'){
        uni.$emit('orderPriceAdjustment', order)
      }else if(this.SupplyChain == 'orderCustomerRename'){
        uni.$emit('orderCustomerRename', order)
      }

      uni.navigateBack({delta: 1});
    }
  },
  mounted() {
    this.loadMoreOrders(); // 初始化加载
  }
};
</script>


<style scoped lang="scss">
.popup-containerd {
  background-color: #f5f5f5;
  //padding: 0 20rpx;
  height: calc(100vh - 10rpx);
}

.search-box {
  background: #fff;
  //border-radius: 12rpx;
  padding: 10rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.popup-scroll {
  overflow-y: auto;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  display: flex;
  flex-direction: column;
  transition: all 0.2s;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.99);
  }
}

.order-info {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-label {
  color: #666;
  width: 140rpx;
}

.order-value {
  color: #333;
  flex: 1;
  font-weight: 500;
}

.order-arrow {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
}
</style>
